import numpy as np
import csv

def load_data(file_path):
    """
    Load city district statistics
    Columns: district, population, avg_rent, area_km2
    Return: 2D array of shape (districts, 3) containing [population, avg_rent, area_km2]
    """

    data = []
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            reader = csv.reader(file)
            next(reader)  # 跳过表头
            for row in reader:
                data.append([float(x) for x in row[1:]])
    except FileNotFoundError:
        print(f"错误：未找到文件 {file_path}")
        return np.array([])
    except Exception as e:
        print(f"读取文件时发生错误：{e}")
        return np.array([])
    return np.array(data)

def calculate_statistics(data):
    """
    Calculate city metrics statistics
    Return: Dictionary containing mean, median, variance, std for each metric
    """

    if data.size == 0:
        return {
            'means': [],
            'medians': [],
            'variances': [],
            'stds': []
        }
    means = np.mean(data, axis=0)
    medians = np.median(data, axis=0)
    variances = np.var(data, axis=0)
    stds = np.std(data, axis=0)
    return {
        'means': means,
        'medians': medians,
        'variances': variances,
        'stds': stds
    }

def print_results(stats):
    """
    Print formatted results with 4-space indentation
    """
    metrics = ['Population', 'Average Rent', 'Area (km²)']
    for metric, mean, med, var, std in zip(metrics, 
                                         stats['means'],
                                         stats['medians'],
                                         stats['variances'],
                                         stats['stds']):
        print(f"{metric}:")
        print(f"    Average: {mean:.1f}")
        print(f"    Median: {med:.1f}")
        print(f"    Variance: {var:.1f}")
        print(f"    Standard Deviation: {std:.1f}")

# Execution flow
city_data = load_data('zhengzhou.csv')
stats = calculate_statistics(city_data)
print_results(stats)
